import React, { useState, useRef, useEffect } from 'react';
import { Button, Form, DatePicker, Input, Space, Pagination, message, Modal } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import ImportDataModal from './ImportDataModal';
import { DataType } from '../../pages/PDSData';
import DraggableTable from '@/components/DraggableTable';
import { ColumnsType } from 'antd/es/table';
import request from '@/utils/request';

const { RangePicker } = DatePicker;

const UploadContent: React.FC<{ datasetId: number; treeUuid: string }> = ({ datasetId, treeUuid }) => {
  const [tableData, setTableData] = useState<DataType[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [tableScrollY, setTableScrollY] = useState<number>(0);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [importFileList, setImportFileList] = useState<any[]>([]);
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [form] = Form.useForm();
  const [columns, setColumns] = useState<ColumnsType<DataType>>([
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 500,
      ellipsis: { showTitle: false },
    },
    {
      title: '数据大小(MB)',
      dataIndex: 'size',
      key: 'size',
      width: 140,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
      render: (v: number) => v.toFixed(1)
    },
    {
      title: '上传时间',
      dataIndex: 'upload_time',
      key: 'upload_time',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right' as const,
      render: (_: any, record: DataType) => <a onClick={() => handleDelete(record)}>删除</a>
    }
  ]);

  // 删除操作
  const handleDelete = (record: DataType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文件"${record.file_name}"吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await request.post('/PDS/DataSetFileDataDelete', {
            dataset_id: datasetId,
            tree_uuid: treeUuid,
            file_ids: [record.key]
          });
          
          if (response.data.code === 200) {
            message.success('删除成功');
            // 刷新列表
            onFinish(form.getFieldsValue());
          } else {
            message.error(response.data.msg || '删除失败');
          }
        } catch (error) {
          message.error('删除失败');
          console.error('删除文件失败:', error);
        }
      }
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的数据');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const fileIds = selectedRowKeys.map(key => parseInt(key.toString()));
          const response = await request.post('/PDS/DataSetFileDataDelete', {
            dataset_id: datasetId,
            tree_uuid: treeUuid,
            file_ids: fileIds
          });
          
          if (response.data.code === 200) {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            // 刷新列表
            onFinish(form.getFieldsValue());
          } else {
            message.error(response.data.msg || '批量删除失败');
          }
        } catch (error) {
          message.error('批量删除失败');
          console.error('批量删除文件失败:', error);
        }
      }
    });
  };

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42; // antd Table 的 header 高度
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);

      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        (body as HTMLElement).style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  // 监听窗口大小变化
  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);

    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  const handleImportChange = (info: any) => {
    let files = [...info.fileList];
    files = files.slice(-5); // 最多5个文件，可根据需求调整
    setImportFileList(files);
  };

  const handleRemoveImportFile = (file: any) => {
    setImportFileList((prev) => prev.filter((item) => item.uid !== file.uid));
  };

  const fetchFileList = async (params: any) => {
    try {
      setLoading(true);
      const response = await request.get('/PDS/DataSetFileDataList', {
        params
      });
      
      if (response.data.code === 200) {
        const { list, count } = response.data.data;
        setTableData(list.map((item: any) => ({
          key: item.id.toString(),
          file_name: item.file_name,
          size: item.data_size / (1024 * 1024), // 转换为MB
          upload_time: item.create_time,
          creator: item.user_id?.toString() || '-',
          task_type: '', // 默认值
          payload: '', // 默认值
          data_level: '', // 默认值
          collect_start_time: '', // 默认值
          collect_end_time: '', // 默认值
        })));
        setTotal(count);
      } else {
        message.error(response.data.msg || '获取数据失败');
      }
    } catch (error) {
      message.error('获取数据失败');
      console.error('获取文件列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const onFinish = (values: any) => {
    const params: any = {
      dataset_id: datasetId,
      tree_uuid: treeUuid,
      page: current,
      page_size: pageSize,
    };

    if (values.file_name) {
      params.file_name = values.file_name;
    }

    if (values.upload_time_range) {
      params.create_time__gte = values.upload_time_range[0].format('YYYY-MM-DD HH:mm:ss');
      params.create_time__lte = values.upload_time_range[1].format('YYYY-MM-DD HH:mm:ss');
    }

    fetchFileList(params);
  };

  useEffect(() => {
    onFinish(form.getFieldsValue());
  }, [current, pageSize, treeUuid]);

  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys)
  };

  return (
    <div className="data-management-right" style={{ flex: '1', overflow: 'auto', minWidth: 0 }}>
      {/* 顶部筛选区 */}
      <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        <Form.Item name="file_name" label="文件名" style={{ width: 320 }}>
          <Input placeholder="输入文件名或关键词" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="upload_time_range" label="上传时间" style={{ width: 320 }}>
          <RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
        </Form.Item>
        <Form.Item style={{ paddingLeft: 80, width: 320 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
            <Button htmlType="button" onClick={() => form.resetFields()}>
              清除
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 操作按钮区 */}
      <Space style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<UploadOutlined />} onClick={() => setImportModalVisible(true)}>
          上传数据
        </Button>
        <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete}>
          批量删除
        </Button>
      </Space>

      {/* 数据表格 */}
      <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
        <DraggableTable
          loading={loading}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          pagination={false}
          bordered
          size="small"
          tableLayout="fixed"
          scroll={{
            y: tableScrollY,
            x: 'max-content'
          }}
          rowClassName={(_: DataType, index: number) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          onColumnsChange={(columns) => {
            setColumns(columns);
          }}
        />
      </div>

      {/* 分页 */}
      <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
        <Pagination
          current={current}
          pageSize={pageSize}
          total={total}
          showSizeChanger
          pageSizeOptions={['10', '20', '50']}
          onChange={(page, size) => {
            setCurrent(page);
            setPageSize(size!);
          }}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>

      <ImportDataModal
        visible={importModalVisible}
        onCancel={() => setImportModalVisible(false)}
        datasetId={datasetId}
        treeUuid={treeUuid}
        onSuccess={() => {
          setImportModalVisible(false);
          message.success('导入成功');
          onFinish(form.getFieldsValue());
        }}
      />
    </div>
  );
};

export default UploadContent; 